package com.samp.bblock.core.web.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.MediaType;

public class SupportJsonHttpRequest implements InitializingBean {
	
	private static final String FLAG_JSON_BODE_READ = "flag_json_bode_read";
	
	private MediaType _supportedMediaType = MediaType.APPLICATION_JSON;
	
	private String supportedMediaType;
	
	private ContentTypeUtil contentType = new ContentTypeUtil();
	
	public boolean support(HttpServletRequest request){
		MediaType mediaType = contentType.getMediaType(request);
		return this._supportedMediaType.includes(mediaType);
		
	}

	public HttpServletRequest wrapRequest(HttpServletRequest request){
		if( Boolean.TRUE.equals(request.getAttribute(FLAG_JSON_BODE_READ)) ){
			return request;
		}
		request.setAttribute(FLAG_JSON_BODE_READ, Boolean.TRUE);
		return new JsonHttpServletRequestWrapper(request);
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if( this.supportedMediaType != null ){
			this._supportedMediaType = MediaType.parseMediaType(this.supportedMediaType);
		}
		
	}

	public void setSupportedMediaType(String supportedMediaType) {
		this.supportedMediaType = supportedMediaType;
	}

}
